package com.jboost.modules.app.util;

import org.springframework.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CglibBeanCopierUtils {

    /**
     *
     */
    public static Map<String, BeanCopier> beanCopierMap = new ConcurrentHashMap<String, BeanCopier>();

    /**
     * @param source 资源类
     * @param target 目标类
     */
    public static <T, V> V copyProperties(T source, V target) {
        if (source != null && target != null) {
            String beanKey = generateKey(source.getClass(), target.getClass());
            BeanCopier copier = null;
            if (!beanCopierMap.containsKey(beanKey)) {
                copier = BeanCopier.create(source.getClass(), target.getClass(), false);
                beanCopierMap.put(beanKey, copier);
            } else {
                copier = beanCopierMap.get(beanKey);
            }
            copier.copy(source, target, null);
        }
        return target;
    }

    public static <T, V> List<V> copyListProperties(List<T> sourceList, Class<V> clazz) {
        List<V> targetList = new ArrayList<V>();
        if (sourceList != null && !sourceList.isEmpty()) {
            for (T source : sourceList) {
                try {
                    V target = clazz.newInstance();
                    copyProperties(source, target);
                    targetList.add(target);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return targetList;
    }

    private static String generateKey(Class<?> class1, Class<?> class2) {
        return class1.toString() + class2.toString();
    }
}